//145. 二叉树的后序遍历

//#include <stdlib.h>
//
//struct TreeNode {
//    int val;
//    struct TreeNode* left;
//    struct TreeNode* right;
//};
//int TreeSize(struct TreeNode* root)
//{
//    if (NULL == root)
//        return 0;
//
//    return TreeSize(root->left)
//        + TreeSize(root->right) + 1;
//}
//void _postorder(struct TreeNode* root, int* a, int* pi)
//{
//    if (NULL == root)
//        return;
//
//    _postorder(root->left, a, pi);
//    _postorder(root->right, a, pi);
//    a[(*pi)++] = root->val;
//}
//int* postorderTraversal(struct TreeNode* root, int* returnSize) {
//    *returnSize = TreeSize(root);
//    int* a = (int*)malloc(*returnSize * sizeof(int));
//    if (NULL == a)
//        return NULL;
//    int i = 0;
//
//    _postorder(root, a, &i);
//    return a;
//}


#include <vector>
#include <stack>
using namespace std;

struct TreeNode 
{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root)
    {
        stack<TreeNode*> st;
        vector<int> ret;
        TreeNode* cur = root;
        TreeNode* prev = nullptr;


        while (cur || !st.empty())
        {
            while (cur)
            {
                st.push(cur);
                cur = cur->left;
            }
            // top节点的右为空 或者 上一个访问节点等于他的右孩子
            // 那么说明(空)不用访问 或者 (不为空)右子树已经访问过了
            TreeNode* top = st.top();
            if (top->right == nullptr || top->right == prev)
            {
                st.pop();
                ret.push_back(top->val);
                prev = top;
            }
            else
            {
                // 右子树不为空，且没有访问，子问题访问右子树
                cur = top->right;
            }
        }
        return ret;
    }
};